package com.xxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxy.entity.User;
import com.xxy.entity.dto.UserQueryDTO;
import com.xxy.mapper.UserMapper;
import com.xxy.result.PageResult;
import com.xxy.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User selectByUsername(String username) {
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, username);
        return userMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public PageResult query(UserQueryDTO userQueryDTO) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        //nickname 模糊查询
        if (userQueryDTO.getNickname()!=null && !userQueryDTO.getNickname().isEmpty()) {
            queryWrapper.like(User::getNickname,userQueryDTO.getNickname());
        }
        if (userQueryDTO.getUsername()!=null && !userQueryDTO.getUsername().isEmpty()) {
            queryWrapper.like(User::getUsername,userQueryDTO.getUsername());
        }
        // 如果没有传 current 或 size，查询全部
        if (userQueryDTO.getCurrent() == null || userQueryDTO.getSize() == null) {
            List<User> allRecords = userMapper.selectList(queryWrapper);
            return new PageResult(allRecords.size(), allRecords);
        }
        Page<User> page = new Page<>(userQueryDTO.getCurrent(), userQueryDTO.getSize());

        Page<User> resultPage = userMapper.selectPage(page, queryWrapper);
        List<User> records = resultPage.getRecords();
        long total = resultPage.getTotal();
        return new PageResult(total, records);
    }
}
